<template>
  <el-form label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        placeholder="请输入SPU名称"
        v-model="spuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="spuParams.tmId">
        <el-option
          :label="item.tmName"
          v-for="(item, index) in allTradeMark"
          :key="item.id"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" v-model="spuParams.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload
        v-model:file-list="imgList"
        list-type="picture-card"
        action="/api/admin/product/fileUpload"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="beforeAvatarUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <!-- 预览放大 -->
      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select v-model="saleAttrIdAndValueName">
        <el-option
          :label="item.name"
          v-for="(item, index) in unSelectSaleAttr"
          :key="item.id"
          :value="`${item.id}:${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        :disabled="saleAttrIdAndValueName ? false : true"
        type="primary"
        icon="Plus"
        style="margin-left: 10px"
        @click="addSaleAttr"
      >
        添加属性
      </el-button>
      <el-table border style="margin: 10px 0px" :data="saleAttr">
        <el-table-column
          label="序号"
          type="index"
          align="center"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="属性名"
          align="center"
          prop="saleAttrName"
        ></el-table-column>
        <el-table-column label="属性值" align="center">
          <template #="{ row, column, $index }">
            <el-tag
              style="margin-right: 10px"
              v-for="(item, index) in row.spuSaleAttrValueList"
              :key="item.id"
              class="mx-1"
              closable
              :type="item.type"
              @close="row.spuSaleAttrValueList.splice(index, 1)"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              @blur="toLook(row)"
              v-model="row.saleAttrValue"
              v-if="row.flag == true"
              placeholder="请输入属性值"
              size="small"
              style="width: 100px"
            ></el-input>
            <el-button
              v-else
              @click="toEdit(row)"
              type="primary"
              size="small"
              icon="Plus"
              style="margin-left: 5px"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120px">
          <template #="{ row, column, $index }">
            <el-button
              size="small"
              type="danger"
              @click="saleAttr.splice($index, 1)"
              icon="Delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        :disabled="saleAttr.length > 0 ? false : true"
        type="primary"
        size="default"
        @click="save"
      >
        保存
      </el-button>
      <el-button size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type {
  HasSaleAttr,
  SaleAttr,
  SpuImg,
  Trademark,
  SpuData,
  AllTradeMark,
  SpuHasImg,
  SaleAttrResponseData,
  HasSaleAttrResponseData,
  SaleAttrValue,
} from '@/api/product/spu/type'
import {
  reqAllTradeMark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAllSaleAttr,
  reqAddOrUpdateSpu,
} from '@/api/product/spu/index'

const $emit = defineEmits(['changeScene'])

// 存储已有的spu数据
const allTradeMark = ref<Trademark[]>([])
const imgList = ref<SpuImg[]>([])
const saleAttr = ref<SaleAttr[]>([])
const allSaleAttr = ref<HasSaleAttr[]>([])
// 存储已有的SPU对象 TODO
const spuParams = ref<SpuData>({
  category3Id: '',
  spuName: '',
  description: '',
  tmId: '',
  spuImageList: [],
  spuSaleAttrList: [],
})
const saleAttrIdAndValueName = ref<string>()
const dialogVisible = ref<boolean>(false)
const dialogImageUrl = ref<string>('')
// 子组件书写方法
const initHasSpuData = async (spu: SpuData) => {
  spuParams.value = spu
  // 获取全部品牌数据
  const result: AllTradeMark = await reqAllTradeMark()
  if (result.code == 200) {
    allTradeMark.value = result.data
  }
  // 获取某一个品牌旗下全部售卖商品的图片
  const result1: SpuHasImg = await reqSpuImageList(spu.id as number)
  if (result1.code == 200) {
    imgList.value = result1.data.map((item) => {
      // name url 是照片墙组件定义的
      return {
        name: item.imgName,
        url: item.imgUrl,
      }
    })
  }
  // 获取已有Spu销售属性的数据
  const result2: SaleAttrResponseData = await reqSpuHasSaleAttr(
    spu.id as number,
  )
  if (result2.code == 200) {
    saleAttr.value = result2.data
  }
  // 获取已有Spu销售属性的数据
  const result3: HasSaleAttrResponseData = await reqAllSaleAttr()
  if (result3.code == 200) {
    allSaleAttr.value = result3.data
  }
}

const handlePictureCardPreview = (file: any) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}
const handleRemove = () => {
  //   console.log(123)
}

const beforeAvatarUpload = (rawFile: any) => {
  if (
    rawFile.type !== 'image/jpeg' ||
    rawFile.type !== 'image/png' ||
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('Upload picture must be JPG|PNG|GIF format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 3) {
    ElMessage.error('Upload picture size can not exceed 3MB!')
    return false
  }
  return true
}
// 计算出当前spu还未拥有的销售属性
const unSelectSaleAttr = computed(() => {
  const unSelectArr = allSaleAttr.value.filter((item: any) => {
    return saleAttr.value.every((item1: any) => {
      return item.name != item1.saleAttrName
    })
  })
  return unSelectArr
})
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  const newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }
  // 追加到数组当中
  saleAttr.value.push(newSaleAttr)
  // 清空收集的数据
  saleAttrIdAndValueName.value = ''
}
const toEdit = (row: SaleAttr) => {
  row.flag = true
}
// 表单input元素失去焦点时的回调
const toLook = (row: SaleAttr) => {
  const { baseSaleAttrId, saleAttrValue } = row
  const newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  }
  // 判空和重复 然后追加新的属性值对象
  if ((saleAttrValue as string).trim() == '') {
    ElMessage.error('属性不能为空')
    return
  }
  const repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == saleAttrValue
  })
  if (repeat) {
    ElMessage.error('属性值重复')
    return
  }
  row.spuSaleAttrValueList.push(newSaleAttrValue)
  row.flag = false
}
// 保存按钮的回调
const save = async () => {
  // 1.照片墙数据
  spuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  //2.整理销售属性的数据
  spuParams.value.spuSaleAttrList = saleAttr.value
  let result = await reqAddOrUpdateSpu(spuParams.value)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: spuParams.value.id ? '更新成功' : '添加成功',
    })
    // 通知父组件切换场景 ; 需要根据是save还是update，来确定是回到当前页还是回到首页
    $emit('changeScene', {
      flag: 0,
      params: spuParams.value.id ? 'update' : 'add',
    })
  } else {
    ElMessage({
      type: 'error',
      message: spuParams.value.id ? '更新失败' : '更新失败',
    })
  }
}
// 点击取消按钮：通知父组件切换场景为1，展示有的SPU的数据
const cancel = () => {
  // 取消留在当前页
  $emit('changeScene', { flag: 0, params: 'update' })
}
// 添加一个新的SPU初始化请求方法
const initAddSpu = async (c3Id: number | string) => {
  // 清空数据
  Object.assign(spuParams.value, {
    category3Id: '',
    spuName: '',
    description: '',
    tmId: '',
    spuImageList: [],
    spuSaleAttrList: [],
  })
  // 清空照片
  imgList.value = []
  // 清空销售属性
  saleAttr.value = []
  // 清空收集的数据
  saleAttrIdAndValueName.value = ''
  // 存储三级分类的ID
  spuParams.value.category3Id = c3Id
  // 获取全部品牌的数据
  const result: AllTradeMark = await reqAllTradeMark()
  const result1: HasSaleAttrResponseData = await reqAllSaleAttr()
  // 存储数据
  allTradeMark.value = result.data
  allSaleAttr.value = result1.data
}
defineExpose({ initHasSpuData, initAddSpu })
// 对外暴露
</script>

<style scoped></style>
